package git.soulbgm.controller;

import git.soulbgm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Pattern;

/**
 * 用户控制器
 *
 * @author SoulBGM
 * @date 2021/04/12
 */
@RequestMapping("user")
@RestController
public class UserController {

    @Autowired
    private MongoTemplate template;

    @GetMapping("findAll")
    public List<User> findAll() {
        return template.findAll(User.class);
    }

    @PostMapping("save")
    public User save(@RequestBody User user) {
        return template.save(user);
    }

    @GetMapping("findById")
    public User findById(Long id) {
        return template.findById(id, User.class);
    }

    @GetMapping("findOne")
    public User findOne(User user) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(user.getName()));
        query.addCriteria(Criteria.where("id").is(user.getId()));
        return template.findOne(query, User.class);
    }

    @DeleteMapping("removeById")
    public long removeById(Long id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return template.remove(query, User.class).getDeletedCount();
    }

    @PutMapping("updateById")
    public long updateById(@RequestBody User user) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(user.getId()));
        Update update = new Update();
        update.set("name", user.getName());
        return template.updateMulti(query, update, User.class).getModifiedCount();
    }

    @GetMapping("find")
    public List<User> find(User user) {
        Query query = new Query();
        Pattern compile = Pattern.compile("^.*" + user.getName() + ".*$");
        query.addCriteria(Criteria.where("name").regex(compile));
        return template.find(query, User.class);
    }
}
